import {CustomStyle, upImage,submitText } from '../../../config/api';
import apiService from '../../../utils/api-service'; 
import { Config } from '../../../config/api.js';
import apiResult from '../../../utils/api-result';



Page({
  data: {
    topImage: CustomStyle.topImage,
    formats: {},
    readOnly: false,
    placeholder: '开始输入...',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
    title:'',
    originalContent:'',
    dialogVisible:true
    
  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  titleInput(e){
    // console.log(e)
    this.setData({
      title:  e.detail.value
    });
  },
  showDialog(){
    this.setData({
      dialogVisible:false
    })
    console.log(this.data.dialogVisible)
  },
  hideDialog(){
    this.setData({
      dialogVisible: true
    })
  },
  getTextValue(html){
    console.log(html)
    this.setData({
      originalContent:html.detail.html
    })
  },
  onLoad() {
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({ isIOS })
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
  },
  //提交发布
  submit(){
    console.log(this.data.title)
    let that = this
    let data = {
      "title":this.data.title,
      "originalContent": this.data.originalContent,
      "status": "PUBLISHED",
      "categoryIds": [],
      "tagIds": [],
      "metas": []
    }
    // try{
    //  const res =  apiService.textUpload(JSON.stringify(data))
    //   that.setData({
    //       dialogVisible:true
    //   })
    //   apiResult.success("发布成功");
    // }catch(e){

    // }
    wx.request({
      url: submitText(wx.getStorageSync(Config.Token)) , 
      method:'post',
      data:data,
      success(res) {
        console.log(res)
        if (res.statusCode == 200){
          apiResult.success("发布成功");
        }else{
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 4000
          })
        }
        that.setData({
          dialogVisible:true
        })
      }
    })

  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const { windowHeight, platform } = wx.getSystemInfoSync()
    const app = getApp().globalData.CustomBar
    // console.log(keyboardHeight, 'keyboardHeight', wx.getSystemInfoSync())
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight-app) : windowHeight-app
    this.setData({ editorHeight, keyboardHeight })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const { statusBarHeight, platform } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    console.log(e)
    const formats = e.detail
    this.setData({ formats })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 1,
      success: res => {
        var tempFilePaths = res.tempFilePaths;
        //这是是上传图片的代码
        wx.uploadFile({
          url: upImage(wx.getStorageSync(Config.Token)),//上传接口
          name: "file",
          // formData: { "subfolder": "active" },
          filePath: tempFilePaths[0],
          complete: function (str) {
            if (str.statusCode == 200) {
              var info = JSON.parse(str.data);
              console.log(info)
              apiResult.success("上传成功");
              //siteInfo.siteroot.replace('/app/index.php', '') + info.data.data 这段代码是拼接完整图片路径
              that.editorCtx.insertImage({
                src: info.data.path,
                width: '100%',
                data: {
                  id: 'abcd',
                  role: 'god'
                },
                success: () => {
                  console.log('insert image success')
                }
              })
            }
          }
        });
      }
    });
  }
})
